package case2;

class NormalBlockingQueue{
    //环形队列
    private String[] data = new String[1000];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public void put(String elem){
        if(size == data.length){
            return ;
        }
        data[tail++] = elem;
        if(tail == data.length){
            tail = 0;
        }
        size++;
    }

    public String take(){
        if(size == 0){
            return null;
        }
        String ret = data[head++];
        if(head == data.length){
            head = 0;
        }
        size--;
        return ret;
    }
}

class MYBlockingQueue{
    //阻塞队列
    private String[] data = new String[1000];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while(size == data.length){
                this.wait();
            }
            data[tail++] = elem;
            if(tail == data.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }

    public String take() throws InterruptedException {
       synchronized (this){
           while(size == 0){
               this.wait();
           }
           String ret = data[head++];
           if(head == data.length){
               head = 0;
           }
           size--;
           this.notify();
           return ret;
       }
    }
}

public class Demo2 {
    public static void main(String[] args) {
        //消费者-生产者模型
        MYBlockingQueue queue = new MYBlockingQueue();

        //消费者
        Thread t1 = new Thread(() -> {
           while(true){
               try {
                   String result = queue.take();
                   System.out.println("消费元素：" + result);
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        //生产者
        Thread t2 = new Thread(() -> {
           int num = 1;
           while(true){
               try {
                   queue.put(num + "");
                   System.out.println("生产元素：" + num);
                   num++;
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               System.out.println();
           }
        });

        t1.start();
        t2.start();
    }
}
